package com.qsboss.demo.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.qsboss.demo.domain.Result;
import com.qsboss.demo.pojo.TbBill;
import com.qsboss.demo.pojo.TbPrompt;
import com.qsboss.demo.pojo.TbUser;
import com.qsboss.demo.service.SmsService;
import com.qsboss.demo.service.TbBillService;
import com.qsboss.demo.service.TbUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author 军哥
 * @version 1.0
 * @description: 费用账单控制层
 * @date 2023/10/25 10:10
 */

@Controller
@Slf4j
@RequestMapping(value = "/bill")
public class TbBillController {

    @Autowired
    TbBillService tbBillService;

    @Autowired
    SmsService smsService;

    @Autowired
    TbUserService tbUserService;

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    JmsTemplate jmsTemplate;

    /***
     * @description 提交销账申请
     * @return com.qsboss.demo.domain.Result
     * @author 军哥
     * @date 2023/10/25 20:23
     */
    @PostMapping(value = "/submitClose")
    @ResponseBody
    public Result submitClose(Integer billId) {
        return tbBillService.submitClose(billId);
    }

    @PostMapping(value = "/sendMobile")
    @ResponseBody
    public Result sendMobile(Integer billId) {
        log.info("发送账单通知短信~~~~~");
        // 获取账单
        TbBill tbBill = tbBillService.getBillById(billId);
        if(tbBill == null) {
            return Result.FAILED(404, "账单不存在");
        }

        // 获取客户信息
        TbUser tbUser = tbUserService.getUserById(tbBill.getCustomerId());
        if(tbUser == null) {
            return Result.FAILED(404, "客户不存在");
        }

        // 发送短信
        String code = RandomUtil.randomString("0123456789", 4);
        System.out.println("发送短信码：" + code);
        Result result = smsService.sendSms(tbUser.getUserMobile(), code);

        return result;
    }

    @PostMapping(value = "/sendPrompt")
    @ResponseBody
    public Result sendPrompt(Integer billId) {
        log.info("发送催款通知~~~~~");
        // 获取账单
        TbBill tbBill = tbBillService.getBillById(billId);
        if(tbBill == null) {
            return Result.FAILED(404, "账单不存在");
        }

        // 获取客户信息
        TbUser tbUser = tbUserService.getUserById(tbBill.getCustomerId());
        if(tbUser == null) {
            return Result.FAILED(404, "客户不存在");
        }

        // 发送activemq消息
        TbPrompt tbPrompt = new TbPrompt();
        tbPrompt.setBillId(tbBill.getBillId());
        tbPrompt.setCustomerId(tbBill.getCustomerId());
        tbPrompt.setCustomerName(tbBill.getCustomerName());
        tbPrompt.setCustomerMail(tbUser.getUserMail());
        tbPrompt.setOptId(tbBill.getOptId());
        tbPrompt.setOptName(tbBill.getOptName());
        tbPrompt.setPayAmount(tbBill.getBillAmount());
        tbPrompt.setBillName(tbBill.getBillName());

        jmsTemplate.convertAndSend(new ActiveMQQueue("bossBill"), JSON.toJSONString(tbPrompt));


        return Result.SUCCESS();
    }

    @PostMapping(value = "/sendMail")
    @ResponseBody
    public Result sendMail(Integer billId) {
        log.info("发送账单通知邮件~~~~~");
        // 获取账单
        TbBill tbBill = tbBillService.getBillById(billId);
        if(tbBill == null) {
            return Result.FAILED(404, "账单不存在");
        }

        // 获取客户信息
        TbUser tbUser = tbUserService.getUserById(tbBill.getCustomerId());
        if(tbUser == null) {
            return Result.FAILED(404, "客户不存在");
        }

        //-- 邮件发送密码
        try {
            //-- 创建邮件对象
            MimeMessage message = javaMailSender.createMimeMessage();

            //-- 创建helper
            MimeMessageHelper helper = new MimeMessageHelper(message);

            //-- 设置邮件的内容
            helper.setFrom("3350996729@qq.com");
            helper.setTo(tbUser.getUserMail());
            String title = "尊敬的" + tbUser.getNickName() + "用户，您的账单请查收";
            helper.setSubject(title);

            String body = "费用说明：" + tbBill.getBillName() + "<br>您的费用是：" + tbBill.getBillAmount() + "元。<br>";
            body += "请 <a href='http://localhost:8080/bill/ackMail.do?billId=" + tbBill.getBillId() + "'>点击确认</a>!!!";

            helper.setText(body);

            //-- 发送邮件
            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
            return Result.FAILED(500, "发送未知错误");
        } finally {
        }

        // 设置邮件发送标志
        tbBillService.setMailSend(billId, 1);

        return Result.SUCCESS();
    }

    /***
     * @description 设置已发送邮件标识
     * @return com.qsboss.demo.domain.Result
     * @author 军哥
     * @date 2023/10/26 21:03
     */
    @GetMapping(value = "/ackMail")
    @ResponseBody
    public Result ackMail(Integer billId) {
        return tbBillService.setAckMail(billId, 2);
    }

    @PostMapping(value = "/getCustomerNeedPay")
    @ResponseBody
    public Result getCustomerNeedPay() {
        return tbBillService.getCustomerNeedPay();
    }

    @GetMapping(value = "/exportBill")
    public void exportBill(HttpServletRequest request, HttpServletResponse response, String billDate) throws IOException {
        // 设置响应的内容类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        // 设置响应的文件名
        String fileName = "bill-" + billDate + ".xls";
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        HSSFWorkbook hssfWorkbook = tbBillService.exportBill(billDate);

        // 将工作簿写入响应流
        try (OutputStream outputStream = response.getOutputStream()) {
            hssfWorkbook.write(outputStream);
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭文档
        hssfWorkbook.close();
    }
}
